package com.jinhua.config;



import com.jinhua.mybatis.util.MybatisPlus;
import com.jinhua.mybatis.util.MybatisPlusBuild;
import io.netty.util.concurrent.FastThreadLocal;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 获取Id的工具类
 */
public class IdUtil {

	private static final FastThreadLocal<Long> idCache = new FastThreadLocal<>();
	private static final FastThreadLocal<Long> totalCache = new FastThreadLocal<>();
//	private static Log logger = Log.getInstance(IdUtil.class);
	protected static final Logger logger = LogManager.getLogger();


	private IdUtil() {

	}

	public static Long getId() {

		Long id = idCache.get();
		if (id == null) {
			logger.warn("当前线程={} 获取不到Id,请检查是否设置", Thread.currentThread().getName());
		} else {
			idCache.remove();
		}

		return id;
	}

	public static void setId(Long id) {
		if (id == null || id <= 0) {
			logger.warn("所传Id不符合规范 Id={}", id);
			return;
		}
		idCache.set(id);

	}

	public static long getTotal() {
		Long total = totalCache.get();
		if (total != null) {
			totalCache.remove();
		} else {
			total = 0L;
		}
		return total;
	}

	private static void setTotal(long total) {
		totalCache.set(total);

	}

	public static long setTotal(MybatisPlusBuild build) {
		long count = MybatisPlus.getInstance().count(build.cached());
		setTotal(count);
		return count;
	}


}


